import os
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt


# 图片上传接口
@csrf_exempt
def course_upload(request):
    msg = {}
    if request.method == 'POST':
        FileOperation.handle_upload_file(request.FILES.get('file'), str(request.FILES['file']))
        msg['msg'] = '上传成功'
        msg['success'] = True
        msg['filepath'] = FileOperation.upload_file_path(request.FILES.get('file'), str(request.FILES['file']))
        msg['filename'] = FileOperation.upload_file_name(request.FILES.get('file'), str(request.FILES['file']))
    return JsonResponse(msg)


# 视频上传接口
@csrf_exempt
def video_upload(request):
    msg = {}
    if request.method == 'POST':
        FileOperation.handle_upload_video(request.FILES.get('file'), str(request.FILES['file']))
        msg['msg'] = '上传成功'
        msg['success'] = True
        msg['videopath'] = FileOperation.upload_video_path(request.FILES.get('file'), str(request.FILES['file']))
    return JsonResponse(msg)


# 图片/视频存储方法
class FileOperation:
    @staticmethod
    def handle_upload_file(file, filename):
        path = r'./templates/fengmian/'  # 图片保存路径
        print(f"filename={filename}")
        if not os.path.exists(path):
            os.makedirs(path)
        with open(path + filename, 'wb') as destination:
            for chunk in file.chunks():
                # print(chunk)
                destination.write(chunk)

    @staticmethod
    def handle_upload_video(file, filename):
        path = r'./templates/video/'  # 视频保存路径
        print(f"filename={filename}")
        if not os.path.exists(path):
            os.makedirs(path)
        with open(path + filename, 'wb') as destination:
            for chunk in file.chunks():
                # print(chunk)
                destination.write(chunk)

    # return图片存储路径
    @staticmethod
    def upload_file_path(file, filename):
        path = r'./media/fengmian/' + f"{filename}"
        return path

    # return视频存储路径
    @staticmethod
    def upload_video_path(file, filename):
        path = r'./media/video/' + f"{filename}"
        return path

    @staticmethod
    def upload_file_name(file, filename):
        name = f"{filename}"
        return name
